//
//  HamatonFirmwareUpgradeViewController.swift
//  hamaton-app
//
//  Created by intyt on 2024/4/26.
//  固件升级

import UIKit
import SnapKit

class HamatonFirmwareUpgradeViewController: HamatonBaseViewController, UIDocumentPickerDelegate {
    var showFileName: Bool = false // 是否显示文件名称
    var editionStr: String = "" // 版本
    var selectedFileURL: URL? // 保存用户选择的文件URL
    weak var delegate: HamatonFirmwareUpgradeDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "固件升级"
        let margTop: Float = 15
        let margRight: Float = -20
        let margLeft: Float = 20
        
        // 版本
        view.addSubview(editionImg)
        view.addSubview(editionLabel)
        // 上传文件
        view.addSubview(uploadFileBtn)
        // 文件名
        view.addSubview(fileNameLabel)
        // 文件删除按钮
        view.addSubview(fileDelImg)
        // 加载图片
        view.addSubview(fileLoadingImg)
        view.addSubview(isLoadingLabel)
        // 默认不显示文件名
        fileNameLabel.isHidden = true
        fileDelImg.isHidden = true
        // 加载图片默认不显示
        fileLoadingImg.isHidden = true
        isLoadingLabel.isHidden = true
        
        
        // 版本
        editionImg.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(margTop*14)
            make.left.equalToSuperview().offset(110)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        editionLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(margTop*14)
            make.left.equalTo(editionImg.snp.right).offset(margLeft)
            make.width.equalTo(160)
            make.height.equalTo(24)
        }
        // 上传文件
        uploadFileBtn.snp.makeConstraints { make in
            make.top.equalTo(editionLabel.snp.bottom).offset(margTop*10)
            make.left.equalToSuperview().offset(88)
            make.right.equalToSuperview().offset(-88)
            make.height.equalTo(40)
        }
        // 文件名
        fileNameLabel.snp.makeConstraints { make in
            make.top.equalTo(uploadFileBtn.snp.bottom).offset(margTop*3)
            make.left.equalToSuperview().offset(88)
            make.height.equalTo(20)
        }
        // 文件删除
        fileDelImg.snp.makeConstraints { make in
            make.top.equalTo(uploadFileBtn.snp.bottom).offset(margTop*3)
            make.left.equalTo(fileNameLabel.snp.right).offset(margLeft)
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        // 文件加载
        fileLoadingImg.snp.makeConstraints { make in
            make.top.equalTo(editionLabel.snp.bottom).offset(margTop*10)
            make.centerX.equalToSuperview()
            make.width.equalTo(70)
            make.height.equalTo(70)
        }
        isLoadingLabel.snp.makeConstraints { make in
            make.top.equalTo(fileLoadingImg.snp.bottom).offset(margTop*2)
            make.centerX.equalToSuperview()
            make.height.equalTo(60)
        }
    }
    

    // 版本
    private lazy var editionImg: UIImageView = {
        let view = UIImageView(image: UIImage(named: "VK"))
        return view
    }()
    
    lazy var editionLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex6:0x404040)
        label.font = Theme.Font.size(16)
        label.text = "当前版本：" + editionStr
        label.backgroundColor = .clear
        label.textAlignment = .left
        return label
    }()
    
    // 上传文件
    private lazy var uploadFileBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle(NSLocalizedString("上传文件", tableName: "HamatonLocalizable", comment: ""), for: .normal)
        button.setTitleColor(UIColor(hex6: 0xFFFFFF, alpha: 1.0), for: .normal)
        button.titleLabel!.font = Theme.Font.size(16, bold: true)
        button.addTarget(self, action: #selector(onClickUploadFileButton), for: .touchUpInside)
        button.backgroundColor  = Theme.Color.Background.main
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 5
        return button
    }()
    
    // 文件名
    private lazy var fileNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex6:0x404040)
        label.font = Theme.Font.size(16)
        label.text = ""
        label.backgroundColor = .clear
        label.textAlignment = .center
        return label
    }()
    
    // 删除
    private lazy var fileDelImg: UIImageView = {
        let image = UIImage(named: "del")
        let imageView = UIImageView(image: image)
        // 添加点击手势识别器
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onClickDelButton))
        imageView.addGestureRecognizer(tapGesture)
        imageView.isUserInteractionEnabled = true // 必须设置为 true，才能接收用户交互事件
        return imageView
    }()
    
    // 加载
    private lazy var fileLoadingImg: UIImageView = {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
        if let gifPath = Bundle.main.path(forResource: "loading1", ofType: "gif") {
            if let gifData = try? Data(contentsOf: URL(fileURLWithPath: gifPath)) {
                imageView.image = UIImage.gifImageWithData(gifData)
            }
        }
        return imageView
    }()
    private lazy var isLoadingLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.Background.main
        label.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.bold)
        label.text = "正在进行固件更新，请不要退出当前页面"
        label.backgroundColor = .clear
        label.textAlignment = .left
        return label
    }()
    

    // 上传文件
    @objc func onClickUploadFileButton() {
        if fileNameLabel.text == "" {
            let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
            documentPicker.delegate = self
            present(documentPicker, animated: true, completion: nil)
        } else {
            print("调用上传接口")
            delegate?.firmwareUpgradeSave0(selectedFileURL!)
            uploadFileBtn.isHidden = true
            fileLoadingImg.isHidden = false
            isLoadingLabel.isHidden = false
            fileNameLabel.isHidden = true
            fileDelImg.isHidden = true
        }
        
    }
    // 删除文件
    @objc func onClickDelButton() {
        fileNameLabel.text = ""
        fileNameLabel.isHidden = true
        fileDelImg.isHidden = true
        uploadFileBtn.setTitle("上传文件", for: .normal)
    }
    // 选择文件
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedFileURL = urls.first else {
            print("No file selected.")
            return
        }
        print("Selected file URL: \(selectedFileURL)")
        // 在这里处理选择的文件，比如上传到服务器或者读取文件内容等操作
        // 使用 lastPathComponent 属性获取文件名
        let fileName = selectedFileURL.lastPathComponent
        fileNameLabel.text = fileName
        fileNameLabel.isHidden = false
        fileDelImg.isHidden = false
        uploadFileBtn.setTitle("开始更新", for: .normal)
        self.selectedFileURL = selectedFileURL
        
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("Document picker was cancelled.")
    }
    
    // 升级成功
    func upgradeSuccess() {
        isLoadingLabel.text = "升级成功！"
        let message = "固件更新完成，设备重启，请重新进行连接"
        let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
        weak var weakSelf = self
        let confirmAction = UIAlertAction(title: NSLocalizedString("好的", tableName: "HamatonLocalizable", comment: ""), style: .default) { action in
            weakSelf?.delegate?.upgradeSuccessDisconnect()
            print("确定了")
        }
        // 创建一个 NSMutableParagraphStyle 对象
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10 // 设置行间距
        
        // 创建属性字典
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 16), // 设置字体大小
            .foregroundColor: UIColor.black, // 设置字体颜色
            .paragraphStyle: paragraphStyle // 设置段落样式
        ]
        
        // 创建带有自定义属性的 NSAttributedString
        let attributedMessage = NSAttributedString(string: message, attributes: attributes)
        
        // 设置消息文本
        alertController.setValue(attributedMessage, forKey: "attributedMessage")
        alertController.addAction(confirmAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
}
extension UIImage {
    // 通过 Data 加载动态图
    static func gifImageWithData(_ data: Data) -> UIImage? {
        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
            return nil
        }
        return UIImage.animatedImageWithSource(source)
    }
    
    // 从 CGImageSource 创建动态图
    static func animatedImageWithSource(_ source: CGImageSource) -> UIImage? {
        let count = CGImageSourceGetCount(source)
        var images = [UIImage]()
        var duration: TimeInterval = 0.0
        
        for i in 0..<count {
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                let durationSeconds = UIImage.frameDurationAtIndex(i, source: source)
                duration += durationSeconds
                images.append(UIImage(cgImage: image))
            }
        }
        
        return UIImage.animatedImage(with: images, duration: duration)
    }
    
    // 获取指定帧的持续时
    static func frameDurationAtIndex(_ index: Int, source: CGImageSource) -> TimeInterval {
        var frameDuration: TimeInterval = 0.1
        let cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
        let frameProperties = cfFrameProperties as NSDictionary?
        if let gifProperties = frameProperties?[kCGImagePropertyGIFDictionary] as? NSDictionary,
           let unclampedDelayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime] as? NSNumber {
            frameDuration = unclampedDelayTime.doubleValue
        } else if let gifProperties = frameProperties?[kCGImagePropertyGIFDictionary] as? NSDictionary,
                  let delayTime = gifProperties[kCGImagePropertyGIFDelayTime] as? NSNumber {
            frameDuration = delayTime.doubleValue
        }
        if frameDuration < 0.011 {
            frameDuration = 0.1
        }
        return frameDuration
    }
}
